#include "my_socket_client.h"

#include <arpa/inet.h>
#include <mutex>
#include <string.h>
#include <unistd.h>

sptr<MySocketClient> MySocketClient::GetInstance()
{
    if (instance == nullptr) {
        static std::mutex mutex;
        std::lock_guard<std::mutex> lock(mutex);
        if (instance == nullptr) {
            instance = new MySocketClient();
        }
    }
    return instance;
}


int MySocketClient::Connect(std::string address, uint16_t port)
{
    socketFd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr = {
        .sin_family = AF_INET,
        .sin_port = htons(port),
        .sin_addr = {
            .s_addr = inet_addr(address.c_str())
        },
    };
    return connect(socketFd, (struct sockaddr *)&addr, sizeof(struct sockaddr));
}

void MySocketClient::Send(const struct Message &m)
{
    struct InnerMessage {
        int id;
        char buffer[1024];
    };
    struct InnerMessage im = {.id = m.id};
    strcpy(im.buffer, m.message.c_str());

    write(socketFd, &im, sizeof(im));
}

std::string MySocketClient::Recv()
{
    char buffer[1024] = {};
    read(socketFd, buffer, sizeof(buffer));
    return buffer;
}

void MySocketClient::Disconnect()
{
    close(socketFd);
}
